package club.kingyin.kyblog.core.utils.jcache;


import club.kingyin.config.v2.adapter.PropertiesAdapter;
import club.kingyin.config.v2.component.Leave;
import club.kingyin.config.v2.component.Monitor;
import club.kingyin.config.v2.core.Bootstrap;
import club.kingyin.config.v2.handler.AccurateUpdater;
import club.kingyin.config.v2.handler.PropertiesHandler;
import club.kingyin.config.v2.handler.Recovery;
import club.kingyin.config.v2.imp.Config;
import club.kingyin.config.v2.utils.ExtensionName;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

/**
 * @author : kingyins
 * @version : 1.0
 * @program : Ky-Blog
 * @description : 在此处添加类描述
 * @create : 2021年08月17日 13:18
 **/
@EnableConfigurationProperties(ConfigYml.class)
public class ConfigFactoryBean implements FactoryBean<Config> {

    @Autowired
    private JCacheLog jCache;

    @Autowired
    private ConfigYml configYml;

    @Override
    public Config getObject() throws Exception {
        Bootstrap bootstrap = new Bootstrap();
        PropertiesAdapter.Builder builder = new PropertiesAdapter.Builder();
        assert StringUtils.isNotEmpty(configYml.getName()):"Jcache文件名不能为空";

        if (StringUtils.isNotEmpty(configYml.getFolder()))
            builder.setFolder(configYml.getFolder());
        jCache.createLog().info("监听路径：{}",configYml.getPath());
        builder.setPath(configYml.getPath());

        if (StringUtils.isNotEmpty(configYml.getDesc()))
            builder.setDesc(configYml.getDesc());
        builder.setExtension(ExtensionName.PROPERTIES);
        builder.setName(configYml.getName());
        builder.setContext(ConfigFactoryBean.class);

        bootstrap.architectCore()
                .setLeave(Leave.LOCAL)
                .setMonitor(Monitor.DEFAULT)
                .addIOHandler(new PropertiesHandler(builder.build(), Leave.LOCAL));
        if (configYml.isRecovery())
            bootstrap.architectVariator().addDeleter(new Recovery());
        switch (configYml.getMonitor()) {
            case "acc":
                bootstrap.architectVariator().addUpdater(new AccurateUpdater());
                break;
            case "def":
                // 新起点啊
                bootstrap.architectVariator().addUpdater((o,n,r)-> o);
            default:
                break;
        }
        return bootstrap.addLogHandler(jCache).build();
    }

    @Override
    public Class<?> getObjectType() {
        return Config.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
